package com.yenlien.traceyun.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.bean.Search;
import com.yenlien.traceyun.business.dao.RecallChainDao;
import com.yenlien.traceyun.business.dao.RecallDao;
import com.yenlien.traceyun.business.entity.Recall;
import com.yenlien.traceyun.business.entity.RecallChain;
import com.yenlien.traceyun.business.service.RecallService;
import com.yenlien.traceyun.webase.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-12-18
 * @description:
 **/

@RestController
    @RequestMapping(value = "/recall")
public class RecallController extends BaseController {

    @Autowired
    private RecallService recallService;

    @Autowired
    private RecallDao recallDao;

    @Autowired
    private RecallChainDao recallChainDao;

    @PostMapping("/add")
    public Object recall(@RequestBody JSONObject params) throws Exception {
        Recall recall = params.getJSONObject("recall").toJavaObject(Recall.class);
        List<RecallChain> chains = params.getJSONArray("chains").toJavaList(RecallChain.class);
        return success(recallService.save(recall, chains));
    }


    // 果园二期召回
    @PostMapping("/addFruitRecall")
    public Object addFruitRecall(@RequestBody Recall recall) {
        return success(recallService.addFruitRecall(recall));
    }


    @GetMapping("/findRecallById")
    public Object findRecallById(String id) {
        return success(recallService.findRecallById(id));
    }


    @PostMapping("/findRecallPageList")
    public Object findRecallPageList(@RequestBody Search search) {
        return success(recallService.findRecallPageList(search));
    }


    @GetMapping("/findRecallByCompId")
    public Object findRecallByCompId(String companyId) {
        return success(recallService.findRecallByCompId(companyId));
    }
    // --






    @PostMapping("/page")
    public Object page(@RequestBody Search search) {
        return buildPage(recallService.page(search));
    }

    @GetMapping("/load/{id}")
    public Object load(@PathVariable("id") int id) {
        JSONObject result = new JSONObject();
        result.put("recall", recallDao.findById(id).get());
        result.put("chains", recallChainDao.findByRecallId(id));
        return result;
    }

    @PostMapping("/modify")
    public Object updateContent(@RequestBody JSONObject params) {
        int id = params.getIntValue("id");
        String reason = params.getString("reason");
        recallService.updateReason(id, reason);
        return success("ok");
    }
}
